package com.lvcoding.auth2.auth.shizhan.exception;

import cn.hutool.core.map.MapUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * @author wuyanshen
 * @description 全局异常处理
 */
// @RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Map<String, Object> handleException(Exception ex) {

        Map<String, Object> map = MapUtil.newHashMap();

        //判断异常的类型,返回不一样的返回值
        if (ex instanceof AccessDeniedException) {
            map.put("code", 403);
            map.put("msg", ex.getMessage());

        } else if (ex instanceof AuthenticationException) {
            map.put("code", 401);
            map.put("msg", ex.getMessage());

        } else if (ex instanceof MissingServletRequestParameterException) {
            map.put("code", 500);
            map.put("msg", "请求参数错误(参数类型或参数个数不正确)");

        } else {
            map.put("code", 500);
            map.put("msg", "系统异常，请联系管理员");
        }

        return map;
    }
}
